<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="客户名称" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="请输入客户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['kenuo:treator:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['kenuo:treator:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['kenuo:treator:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['kenuo:treator:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="treatorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户ID" align="center" prop="userId" />
      <el-table-column label="客户名称" align="center" prop="nickName" />
      <el-table-column label="手机号码" align="center" prop="phonenumber" />
      <el-table-column label="所在城市" align="center" prop="city">
        <template slot-scope="scope">
          <span>{{ scope.row.province+scope.row.city+(scope.row.area ? scope.row.area :　"") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="治疗人数量" align="center" prop="">
        <template slot-scope="scope">
          <el-button @click.native.prevent="getUserInfo(scope.row)" type="text" size="small">
            {{ scope.row.treatorList.length }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="绑定设备数量" align="center" prop="">

        <template slot-scope="scope">
          <el-button @click.native.prevent="getDeviceInfo(scope.row)" type="text" size="small">
            {{ scope.row.equList.length }}
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="注册时间" align="center" prop="createTime" width="180">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['kenuo:treator:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['kenuo:treator:remove']">删除</el-button>
          <!--   <el-button size="mini" type="text" icon="el-icon-tickets" @click="getDeviceInfo(scope.row)"
              >绑定设备</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog title="设备列表" :visible.sync="deviceDialog" v-if="deviceDialog"  width="60%" append-to-body>
      <DeviceList :deviceList="deviceList"></DeviceList>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deviceDialogCancel">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog title="治疗人列表" :visible.sync="followUserDialog" width="60%" append-to-body>
      <FollowUserList @updateTeator="updateTeator" :followUserList="followUserList"></FollowUserList>
      <div slot="footer" class="dialog-footer">
        <el-button @click="followUserDialogCancel">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-if="open"  width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户名称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号码" :disabled="title=='添加' ? false : true" />
        </el-form-item>
        <el-form-item label="省" prop="province">
          <el-select v-model="form.province" filterable placeholder="请选择省"
            @change="(value)=>{getGeography1('city',value)}">
            <el-option v-for="item in provinceList" :label="item.name" :key="item.id" :value="item.id+'-'+item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-select v-model="form.city" placeholder="请选择市" @change="(value)=>{getGeography1('area',value)}">
            <el-option v-for="item in cityList" :label="item.name" :key="item.id" :value="item.id+'-'+item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区" prop="area">
          <el-select v-model="form.area" placeholder="请选择区">
            <el-option v-for="item in areaList" :label="item.name" :key="item.id" :value="item.id+'-'+item.name">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div style="color:red">原始密码：kn123456</div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    encrypt,
    decrypt
  } from '@/utils/jsencrypt'
  import {
    getUser,
    listUser,
    addUser,
    updateUser,
    delUser
  } from "@/api/system/user";
  import {
    getGeography
  } from '@/api/kenuo/common'
  import DeviceList from './deviceList'
    import FollowUserList from './followUserList'

  export default {
    name: "Treator",
    components: {
      DeviceList,
      FollowUserList
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 【请填写功能名称】表格数据
        treatorList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          roleIds: [5],
          userType: '003',
          userName: null,
          password: null,
          nickName: null,
          phonenumber: null,
          city: null,
          province: null,
          area: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          nickName: [{
            required: true,
            message: "请填写客户名称",
            trigger: "blur"
          }],
          phonenumber: [{
              required: true,
              message: "请填写联系方式",
              trigger: "blur"
            },
            {
              pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
              message: "请输入合法手机号/电话号",
              trigger: "blur"
            }
          ],
          province: [{
            required: true,
            message: "请选择省",
            trigger: "blur"
          }],
          city: [{
            required: true,
            message: "请选择市",
            trigger: "blur"
          }],
          area: [{
            required: false,
            message: "请选择区",
            trigger: "blur"
          }],
        },
        provinceList: [], //省列表
        cityList: [],
        areaList: [],
        //设备列表
        deviceList: [],
        deviceDialog: false,
        //治疗人列表
        followUserList:[],
        followUserDialog:false,
      };
    },
    created() {
      this.getList();
      this.getGeography1('province', 0)
    },
    methods: {
      // //更新治疗人
      updateTeator(){
        this.getList();
        this.followUserDialog = false
      },
      followUserDialogCancel() {
        this.followUserDialog = false;
      },
      //获取治疗人列表
      getUserInfo(row) {
        // console.log(row.treatorList)
        this.followUserList = row.treatorList
        this.followUserDialog = true
      },
      //获取设备列表
      getDeviceInfo(row) {
        // console.log(row.equList)
        this.deviceList = row.equList
        this.deviceDialog = true
      },

      //关闭
      deviceDialogCancel() {
        this.deviceDialog = false;
      },
      // 获取地理位置
      getGeography1(level, pidName) {
        console.log(level)
        console.log(pidName)
        let pid = ''
        if (pidName == "0") {
          pid = 0
        } else {
          pid = pidName.split('-')[0]
        }
        getGeography({
          pid: pid
        }).then(res => {
          if (res.code == 200) {
            if (level == "province") {
              this.provinceList = res.data
              this.form.city = ''
              this.form.area = ''
            } else if (level == "city") {
              this.cityList = res.data
              this.form.city = ''
              this.form.area = ''
            } else if (level == "area") {
              this.areaList = res.data
              this.form.area = ''
            }

          }
        });
      },
      /** 查询【请填写功能名称】列表 */
      getList() {
        this.loading = true;
        listUser(this.queryParams).then(response => {
          this.treatorList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          treatName: null,
          sex: null,
          age: null,
          leftEyeDegree: null,
          rightEyeDegree: null,
          pup: null,
          createTime: null,
          updateTime: null,
          tel: null,
          city: null,
          remarkOne: null,
          remarkTwo: null,
          remarkThree: null,
          province: null,
          area: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.userId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.getGeography1('city', row.provinceId)
        this.getGeography1('area', row.cityId)
        const userId = row.userId || this.ids
        getUser(userId).then(response => {
          this.form = response.data;

          this.form.province = this.form.provinceId + '-' + this.form.province
          this.form.city = this.form.cityId + '-' + this.form.city
          if(this.form.areaId && this.form.area){
             this.form.area = this.form.areaId + '-' + this.form.area
          }else{
             this.form.area =''
          }

          this.open = true;
          this.title = "修改";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.userName = this.form.phonenumber
            this.form.roleIds = ['5']
            this.form.userType = "003"
            this.form.provinceId = this.form.province.split('-')[0] //id
            this.form.province = this.form.province.split('-')[1]
            this.form.cityId = this.form.city.split('-')[0] //id
            this.form.city = this.form.city.split('-')[1]
            if (!this.form.area && this.areaList.length > 0) {
              this.$modal.msgSuccess("请选择区");
              return
            }
            this.form.areaId = this.form.area.split('-')[0] //id
            this.form.area = this.form.area.split('-')[1]
            console.log(this.form)
            // return
            if (this.form.userId != null) {
              updateUser(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.form.password = encrypt("kn123456") //默认原始密码
              addUser(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.userId || this.ids;
        this.$modal.confirm('是否确认删除该数据项？').then(function() {
          return delUser(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        let obj = {
          userName: null,
          phonenumber: null,
          province: null,
          city: null,
          area: null,
          treatorNum: null,
          snCode: null,
          createTime: null,
          updateTime: null,
          boundTime: null,
          unboundTime: null,
          userType:"003"
        }
        // return
        this.download('system/user/clientExport', {
          ...obj
        }, `${new Date().getTime()}.xlsx`)
        // this.download('kenuo/treator/export', {
        //   ...obj
        // }, `treator_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
